<?php
namespace plugins\rabbitmq\common; 

class DosthController 
{
    static private $config = [
        // Rabbitmq 服务地址
        'host' => '192.168.3.216',
        // Rabbitmq 服务端口
        'port' => '5672',
        // Rabbitmq 帐号
        'login' => 'admin',
        // Rabbitmq 密码
        'password' => 'admin',
        'vhost'=>'/'
    ];
    static private $_instance;
    static private $_conn;
    static private $_channel;
    static private $_queue;
    static private $_route;
    static private $_exchange;


    
    public static function getInstance()
    {
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self(self::$config);
            return self::$_instance;
        }
    }

    private  function __construct($config)
    {
        //创建连接和channel
        $conn = new AMQPConnection($config);
        if(!$conn->connect()) {
            die("Cannot connect to the broker!\n");
        }
        self::$_channel = new AMQPChannel($conn);
        self::$_conn = $conn;
    }
    private function __clone(){}

    //创建队列
    private static function setQueue($queueName,$exchangeName,$routingKey){
        //  创建队列
        $q = new AMQPQueue(self::$_conn);
        $q->setName($queueName);
        $q->setFlags(AMQP_DURABLE);
        $q->declareQueue();

        // 用于绑定队列和交换机
        self::$_route = $routingKey;
        $q->bind($exchangeName,  $routingKey);
        self::$_queue = $q;
        return $q;
    }
    //连接交换机
    public function setExchange($exchangeName,$queueName,$routingKey){
        //创建交换机
        $ex = new AMQPExchange(self::$_conn);
        self::$_exchange = $ex;
        $ex->setName($exchangeName);

        $ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型
        $ex->setFlags(AMQP_DURABLE); //持久化
        $ex->declare();
        return self::setQueue($queueName,$exchangeName);
    }

    
    public function consumer($exchangeName,$queueName,$routingKey){
        self::$_queue = $queueName;
        $queue = $this->setExchange($exchangeName,$queueName,$routingKey);

        while(true)
        {
            $message = $queue->get();
            if(!empty($message))
            {
                echo $message->getBody();
                $queue->ack($message->getDeliveryTag());    //应答，代表该消息已经消费
                // sleep(3);
                // exit();
            }
            else
            {
                // $this->conn->disconnect();
                // exit();
                //echo 'message not found' . PHP_EOL;
            }
        }
    }
}

DosthController::getInstance()->consumer('e_linvo1','q_ttt','key_2');